package gui.action;

import gui.Activator;
import gui.editor.RoomGlobalChatEditor;
import gui.editor.RoomGlobalChatEditorInput;
import gui.entity.RoomEntity;

import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.SelectionProviderAction;

public class OpenRoomAction extends SelectionProviderAction {
	public final static String ID = "gui.action.OpenRoomAction";

	public OpenRoomAction(final ISelectionProvider provider) {
		super(provider, "&OpenRoomAction");
		setId(ID);
		setText("&OpenRoomAction");
		setToolTipText("Open this room.");
	}

	public void run() {
		IStructuredSelection structuredSelection = getStructuredSelection();
		Object firstElement = structuredSelection.getFirstElement();
		openEditor(((RoomEntity) firstElement).getRoom().name);
	}

	public static IEditorPart openEditor(final String roomName) {
		IWorkbench workbench = PlatformUI.getWorkbench();
		IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
		IWorkbenchPage activePage = window.getActivePage();

		RoomGlobalChatEditorInput input = new RoomGlobalChatEditorInput(
				roomName);
		if (input != null) {
			try {
				return activePage.openEditor(input, RoomGlobalChatEditor.ID,
						true);
			} catch (final PartInitException pie) {
				Shell shell = window.getShell();
				ErrorDialog.openError(shell, "Error opening room", pie
						.getMessage(), pie.getStatus());
				Activator.getDefault().getLog().log(pie.getStatus());
			}
		}
		return null;
	}
}